<?php
/**
 * 分类数据模型
 * 
 * @author sandy
 *
 */
class categoryModel extends Model{
	
	/**
	 * 获取分类信息
	 * @param unknown_type $offset
	 * @param unknown_type $limit
	 * @param unknown_type $order
	 */
	public function get_category($parent_id = 0,$page_info = array()){
		
		$return = array('result'=>'','total'=>0);
		
		$where = "";
		if ($parent_id > 0){
			$where = "parent_cat_id = ".$parent_id;
		}
		
		$sql = "SELECT * FROM #__category $where ORDER BY category_id DESC";
		$sql_count = "SELECT count(*) FROM #__category $where";
	
		if (!empty($page_info)){
			$this->db->set_query($sql,$page_info['offset'],$page_info['limit']);
		} else {
			$this->db->set_query($sql);
		}
		
		$return['result'] = $this->db->get_all();
		
		
		$this->db->set_query($sql_count);
		$return['total'] = $this->db->get_one();
		
		return $return;
	}
	
	/**
	 * 获取指定类别信息
	 * @param int $category_id
	 */
	public function get_category_info($category_id){
		$sql = "SELECT * FROM #__category WHERE category_id = " .$category_id;
		$this->db->set_query($sql);
		return $this->db->get_row($sql);
	}
	
	/**
	 * 添加分类
	 * @param unknown_type $info
	 */
	public function add_category($info){
		
		$insert_info = array(
				'category' => $info['category'],
				'parent_cat_id'=> $info['parent_cat_id'],
				'depth' => $info['depth']
		);
		
		return $this->db->insert("#__category",$insert_info);
	}
	
	
	/**
	 * 删除分类
	 */
	public function del_category($category_id){
		$sql = "DELETE FROM #__category WHERE category_id = ".$category_id;
		$this->db->set_query($sql);
		
		return $this->db->query();
	}
	
	/**
	 * 更新分类信息
	 */
	public function update_category($info){
		$update_info = array(
			'category_id' => $info['category_id'],
			'category' => $info['category'],
			'parent_cat_id'=> $info['parent_cat_id'],
			'depth' => $info['depth']
		);
		
		return $this->db->update('#__category',$update_info,'category_id = '.$update_info['category_id']);
		/*
		$sql = "UPDATE #__category SET category = '".$update_info['category'].
		"', parent_cat_id = ".$update_info['parent_cat_id'].
		" WHERE category_id = ".$update_info['category_id'];
		
		$this->db->set_query($sql);		
		return $this->query();
		*/
	}

	
	public function get_category_tree($categories,$select_id = -1,$root_id = 0){
		if ($select_id < 1) $select_id = -1;
	
		$category_tree = array();
		foreach ($categories as $cat){
			$category_tree [] = array(
					'id' => $cat['category_id'],
					'parentid' => $cat['parent_cat_id'],
					'name' => $cat['category']
			);
		}
		import_lib('tree');
		$tree = new tree();
		$tree->init($category_tree);
		$srt = "<option value=\$id \$selected>\$spacer\$name</option>";
		$category_tree = $tree->get_tree($root_id,$srt,$select_id);
	
		return $category_tree;
	}


}




